package com.ts.oss.util;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

public class ImageRotation {
    public static BufferedImage rotateImage(BufferedImage image, double angle) {
        int w = image.getWidth();
        int h = image.getHeight();

        // 计算旋转后图像的新边界
        double sin = Math.sin(Math.toRadians(angle));
        double cos = Math.cos(Math.toRadians(angle));
        int newW = (int) Math.floor(Math.abs(w * cos) + Math.abs(h * sin));
        int newH = (int) Math.floor(Math.abs(h * cos) + Math.abs(w * sin));

        // 创建一个新的BufferedImage对象，用于存储旋转后的图像
        BufferedImage rotatedImage = new BufferedImage(newW, newH, image.getType());

        // 获取Graphics2D对象以进行绘制
        Graphics2D g2d = rotatedImage.createGraphics();

        // 设置渲染提示
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 旋转图像
        AffineTransform at = new AffineTransform();
        at.rotate(Math.toRadians(angle), newW / 2, newH / 2);
        g2d.setTransform(at);

        // 绘制旋转后的图像
        g2d.drawImage(image, (newW - w) / 2, (newH - h) / 2, null);

        // 释放Graphics2D对象的资源
        g2d.dispose();

        return rotatedImage;
    }
}
